<template>
  <view class="ai-checkbox-group" :class="{'ai-checkbox-group--block': block}">
    <ai-checkbox v-for="item in options"
      :text="item.label"
      :value="item.value"
      :checked="values.includes(item.value)"
      :disabled="item.disabled"
      :key="'checkbox-v-' + item.value"
      @change="onchange">
    </ai-checkbox>
  </view>
</template>

<script>
  export default {
    name: "ai-checkbox-group",
    emits: ["change", "update:value"],
    props: {
      options: {
        type: Array,
        default: []
      },
      value: {
        type: Array,
        default: []
      },
      disabled: {
        type: Boolean,
        default: false
      },
      block: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        values: []
      };
    },
    watch: {
      value: {
        handler: function(n, o) {
          let len = this.values.length
          this.values = n || []
        },
        immediate: true
      }
    },
    methods: {
      onchange(e) {
        let v = e.value
        if (e.checked) {
          this.values.push(e.value)
        } else {
          let idx = this.values.indexOf(v)
          this.values.splice(idx, 1);
        }
        this.$emit("change", this.values)
        this.$emit("update:value", this.values)
      }
    },
  }
</script>

<style lang="scss">
  @import "@/styles/_radio_checkbox.scss"
</style>